﻿using DataModels.Entities.HomeService;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System.Drawing;
using System.Text.Json;

namespace ScheduledTasks.HomeService
{
    public class GroupExpires : IScheduledTask
    {
        private readonly ILogger<OrderExpires> _logger;
        private SqlSugarClient _db;

        public GroupExpires(ILogger<OrderExpires> logger)
        {
            _logger = logger;
        }

        // 5秒执行一次
        public string Schedule => "*/1 * * * * *";


        public async Task<Task> ExecuteAsync(SqlSugarClient db)
        { 

            _db = db;
            //处理待支付过期的团购参与者
            await GroupPendingPayment();

            //处理已支付超期的团购参与者 - 退款
            await GroupPaid();
            return Task.CompletedTask;
        }

        private async Task GroupPendingPayment()
        {
            try
            {
                await _db.BeginTranAsync();
                // 查询待支付过期的团购参与者
                List<HomeServiceProductGroupParticipant> hspgp = await _db.Queryable<HomeServiceProductGroupParticipant>()
                    .Where(hspgp => hspgp.Status == DataModels.Enums.Home.GroupParticipantStatus.PendingPayment)
                    .Where(hspgp => hspgp.ExpireTime < DateTime.Now)
                    .ToListAsync()
                    ;
                if (hspgp.Count > 0)
                {
                    _logger.LogInformation("查询到 {Count} 个待支付过期的团购参与者", hspgp.Count);
                    // 更新状态为已取消
                    foreach (var participant in hspgp)
                    {
                        participant.Status = DataModels.Enums.Home.GroupParticipantStatus.Cancelled;
                        participant.UpdateTime = DateTime.Now;
                    }
                    var updateCount = await _db.Updateable(hspgp).ExecuteCommandAsync();
                    _logger.LogInformation("成功更新 {Count} 个团购参与者状态为已取消", updateCount);
                    await _db.CommitTranAsync();
                }
            }
            catch (Exception ex)
            {
                await _db.RollbackTranAsync();
                _logger.LogInformation("处理待支付过期的团购失败：{ msg }", ex.Message);
            }
        }

        private async Task GroupPaid()
        {
            try
            {
                await _db.BeginTranAsync();
                // 查询已支付超期的团购参与者
                List<HomeServiceProductGroupParticipant> hspgp = _db.Queryable<HomeServiceProductGroupParticipant>()
                    .Where(hspgp => hspgp.Status == DataModels.Enums.Home.GroupParticipantStatus.Paid)
                    .Where(hspgp => hspgp.ExpireTime < DateTime.Now)
                    .ToList()
                    ;

                if (hspgp.Count > 0)
                {
                    List<HomeServiceOrder> hsos = _db.Queryable<HomeServiceOrder>()
                        .Where(hso => hspgp.Select(pgp => pgp.HomeServiceOrderUUID).Contains(hso.UUID))
                        .ToList()
                        ;

                    _logger.LogInformation("查询到 {Count} 个已支付过期的团购参与者", hspgp.Count);
                    // 更新状态为已取消
                    foreach (var participant in hspgp)
                    {
                        // ----   退款未实现   ---- //
                        participant.Status = DataModels.Enums.Home.GroupParticipantStatus.Refunded;
                        participant.UpdateTime = DateTime.Now;

                        HomeServiceOrder hso = hsos.Where(o => o.UUID == participant.HomeServiceOrderUUID).First();
                        if (hso != null)
                        {
                            HomeServiceOrderHistory history = JsonSerializer.Deserialize<HomeServiceOrderHistory>(
                                JsonSerializer.Serialize(hso)
                            );
                            history.beizhu = "团购过期取消";
                            await _db.Insertable(history).ExecuteCommandAsync();
                        }
                        else
                        {
                            _logger.LogInformation("团购 {UUID} 没有找到对应的订单，取消订单失败", participant.UUID);
                        }
                    }
                    var updateCount = await _db.Updateable(hspgp).ExecuteCommandAsync();
                    _logger.LogInformation("成功更新 {Count} 个团购参与者状态为已退款", updateCount);
                    await _db.CommitTranAsync();
                }
            }
            catch (Exception ex)
            {
                await _db.RollbackTranAsync();
                _logger.LogInformation("处理已支付过期的团购失败：{ msg }", ex.Message);
            }
        }
    }
}